package com.chat.websocket.util.sms;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.Common;
import com.aliyun.teautil.models.RuntimeOptions;
import com.chat.websocket.exception.GlobalException;
import com.chat.websocket.util.random.RandomUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * SunJingxuan
 * 2022 \ 08 \ 29
 */

@Slf4j
public class AliSendSmsUtil {

    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new com.aliyun.teaopenapi.models.Config()
                // 您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    public static String sendSms(String phone) {
        Client client = null;
        try {
            String code = RandomUtil.getRandomNum(6, false);
            client = AliSendSmsUtil.createClient("LTAI5tSojqbunE8VMN2DMrXm", "y7os6CjqVOhrCAYb5XzrtpESi4zzel");
            SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                    .setSignName("阿里云短信测试")
                    .setTemplateCode("SMS_154950909")
                    .setPhoneNumbers(phone)
                    .setTemplateParam("{\"code\":\"" + code + "\"}");
            RuntimeOptions runtime = new RuntimeOptions();
            try {
                // 复制代码运行请自行打印 API 的返回值
                client.sendSmsWithOptions(sendSmsRequest, runtime);
            } catch (TeaException error) {
                // 如有需要，请打印 error
                log.error(error.getCode() + "");
                log.error(error.getMessage() + "");
                log.error(error.getData() + "");
                Common.assertAsString(error.message);
            } catch (Exception _error) {
                log.error(_error.getMessage());
                TeaException error = new TeaException(_error.getMessage(), _error);
                // 如有需要，请打印 error
                Common.assertAsString(error.message);
                log.error(error.getCode() + "");
                log.error(error.getMessage() + "");
                log.error(error.getData() + "");
            }
            return code;
        } catch (Exception e) {
            throw new GlobalException(e);
        }
    }

    public static void main(String[] args) {
        try {
            AliSendSmsUtil.sendSms("1234");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
